<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <template>
        <el-row class="addUserButton">
          <el-button type="primary" @click="addRulesDialogVisible = true">添加角色</el-button>
        </el-row>
        <!--    添加角色弹窗    -->
        <el-dialog
          title="添加角色"
          :visible.sync="addRulesDialogVisible"
          width="28%"
          @close="colseDialog('addRulesRef')"
        >
          <!--    添加角色表单      -->
          <el-form :model="addRuleForm" :rules="addRuleFormRules" ref="addRulesRef" label-width="90px"
                   class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addRuleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addRuleForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addRulesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRules">确 定</el-button>
          </span>
        </el-dialog>
        <el-table
          :data="rolesList"
          border
          style="width: 100%" stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="[key1 ===0 ? 0 : 'bd_top','bd_top','vertical']" v-for="(item1,key1) in scope.row.children"
                      :key="item1.id">
                <el-col :span="5">
                  <el-tag
                    :key="item1.id"
                    closable style="margin-right: 0"
                    @close="deletAlert('此操作将删除\{'+item1.authName+'\}这个权限, 是否继续?','',item1,'deleteRulesRights',scope.row)"
                  >
                    {{ item1.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <el-row :class="[key2 === 0 ? '' : 'bd_top','vertical']" v-for="(item2,key2) in item1.children"
                          :key="item2.id">
                    <el-col :span="7">
                      <el-tag
                        :key="item1.id"
                        closable
                        type="success" style="margin-right: 0"
                        @close="deletAlert('此操作将删除\{'+item2.authName+'\}这个权限, 是否继续?','',item2,'deleteRulesRights',scope.row)"
                      >
                        {{ item2.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="17">
                      <el-row :class="['vertical']">
                        <el-col :span="24">
                          <el-tag v-for="item3 in item2.children"
                                  :key="item3.id"
                                  closable
                                  type="warning"
                                  @close="deletAlert('此操作将删除\{'+item3.authName+'\}这个权限, 是否继续?','',item3,'deleteRulesRights',scope.row)"
                          >
                            {{ item3.authName }}
                          </el-tag>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            type="index"
            label="#">
          </el-table-column>
          <el-table-column
            label="角色名称"
            prop="roleName">
          </el-table-column>
          <el-table-column
            label="角色描述"
            prop="roleDesc">
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateRuleDialog(scope.row)">编辑
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除角色" placement="top">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="deletAlert('此操作将永久删除\{'+scope.row.roleName+'\}这个角色, 是否继续?','',scope.row,'deleteRules')">
                  删除
                </el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="分配权限" placement="top">
                <el-button type="warning" icon="el-icon-star-off" size="mini"
                           @click="getTreeRightsList(scope.row)">分配权限
                </el-button>
              </el-tooltip>
              <!--        编辑角色弹窗    -->
              <el-dialog
                title="编辑角色"
                :visible.sync="updateRulesDialogVisible"
                width="28%"
                @close="colseDialog('updateRulesRef')"
              >
                <!--    编辑角色表单      -->
                <el-form :model="updateRuleForm" :rules="addRuleFormRules" ref="updateRulesRef" label-width="90px"
                         class="demo-ruleForm">
                  <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="updateRuleForm.roleName"></el-input>
                  </el-form-item>
                  <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="updateRuleForm.roleDesc"></el-input>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="updateRulesDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="updateThisRules">确 定</el-button>
                </span>
              </el-dialog>
              <!--        分配权限弹窗      -->
              <el-dialog
                title="分配权限"
                :visible.sync="updateRightsDialogVisible"
                width="30%"
                @close="RightsTreeClose">
                <el-tree
                  :data="rightsTreeList"
                  show-checkbox
                  :default-expanded-keys="thisRulesRights"
                  :accordion="true"
                  node-key="id"
                  ref="rulesTree"
                  highlight-current
                  :default-checked-keys="thisRulesRights"
                  :props="rightsDefaultProps">
                </el-tree>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="updateRightsDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="updateThisRights()">确 定</el-button>
                </span>
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 权限树形结构列表
      rightsTreeList: [],
      // 树形结构绑定显示模板
      rightsDefaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 角色id
      ruleId: '',
      // 该角色权限
      thisRulesRights: [],
      // 需要修改的权限id数组
      updateThisRulesRights: [],
      // 编辑权限弹框的显示与隐藏
      updateRightsDialogVisible: false,
      // 添加角色弹窗
      addRulesDialogVisible: false,
      // 编辑弹窗
      updateRulesDialogVisible: false,
      // 角色对象
      addRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色需要的储存对象
      updateRuleForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      addRuleFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 删除提示框
    deletAlert (message, title, data, methond, data2 = null) {
      this.$msgbox.confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(data)
        // 删除角色
        if (methond === 'deleteRules') {
          this.deleteRules(data.id)
        }
        // 删除角色指定权限
        if (methond === 'deleteRulesRights') {
          this.deleteRulesRights(data2, data)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 删除角色
    async deleteRules (rulesId) {
      console.log(rulesId)
      const { data: res } = await this.$http.delete('roles/' + rulesId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // ID查看角色信息
    async selectRules (rulesId, form, dialogVisible) {
      // console.log(userId, form, dialogVisible)
      const { data: res } = await this.$http.get('roles/' + rulesId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this[form] = res.data
      this[dialogVisible] = true
    },
    // 删除角色指定权限
    async deleteRulesRights (rules, rights) {
      const { data: res } = await this.$http.delete('roles/' + rules.id + '/rights/' + rights.id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      rules.children = res.data
    },
    // 获取权限树形结构
    async getTreeRightsList (thisRulesRights) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getThisRulesRightsId(thisRulesRights, this.thisRulesRights)
      this.rightsTreeList = res.data
      this.ruleId = thisRulesRights.id
      this.updateRightsDialogVisible = true
    },
    // 重置表单
    colseDialog (refName) {
      this.$refs[refName].resetFields()
    },
    // 修改角色权限
    async updateThisRights () {
      // 选中叶子节点key
      this.updateThisRulesRights = this.$refs.rulesTree.getCheckedKeys()
      // 将半圆角节点key合并叶子节点key
      this.updateThisRulesRights = this.updateThisRulesRights.concat(this.$refs.rulesTree.getHalfCheckedKeys())
      const { data: res } = await this.$http.post('roles/' + this.ruleId + '/rights', { rids: this.updateThisRulesRights.join(',') })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$refs.rulesTree.setCheckedKeys(this.updateThisRulesRights)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.updateRightsDialogVisible = false
    },
    // 添加角色
    async addRules () {
      const { data: res } = await this.$http.post('roles', this.addRuleForm)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.addRulesDialogVisible = false
    },
    // 角色编辑弹窗
    updateRuleDialog (rules) {
      this.updateRuleForm.id = rules.id
      this.updateRuleForm.roleName = rules.roleName
      this.updateRuleForm.roleDesc = rules.roleDesc
      this.updateRulesDialogVisible = true
    },
    // 角色编辑提交
    async updateThisRules () {
      const { data: res } = await this.$http.put('roles/' + this.updateRuleForm.id, this.updateRuleForm)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.updateRulesDialogVisible = false
    },
    // 关闭树形框清空数据
    RightsTreeClose () {
      this.thisRulesRights = []
    },
    // 递归获取级联权限
    getThisRulesRightsId (rights, arr) {
      if (!rights.children) {
        return arr.push(rights.id)
      }
      rights.children.forEach(item =>
        this.getThisRulesRightsId(item, arr)
      )
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.bd_top {
  border-top: 1px solid #eee;
}

.bd_bottom {
  border-bottom: 1px solid #eee;
}

.vertical {
  display: flex;
  align-items: center;
}

.el-row {
  margin-bottom: 0;
}

.addUserButton {
  margin-bottom: 15px;
}
</style>
